package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.cache.service.ILoginInfoCacheService;
import cn.wolfcode.luowowo.cache.service.IVerifyCodeCacheService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Assert;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;


@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference
    private IVerifyCodeCacheService verifyCodeCacheService;
    @Reference
    private ILoginInfoCacheService loginInfoCacheService;

    @Override
    public boolean checkPhone(String phone) {
        return userInfoMapper.checkPhone(phone) == null;
    }

    @Override
    public AjaxResult userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        AjaxResult result = new AjaxResult();
        try {
            //1.非空检测
            Assert.hasLength(nickname, "昵称不能为空");
            Assert.hasLength(password, "密码不能为空");
            Assert.hasLength(rpassword, "确认密码不能为空");
            Assert.hasLength(verifyCode, "验证码不能为空");
            Assert.hasLength(phone, "手机号不能为空");

            //2.验证码判断
            String verifyCode4Redis = verifyCodeCacheService.getVerifyCode(phone);
            Assert.equalsIgnoreCase(verifyCode, verifyCode4Redis, "验证码有误");

            //3.两次密码判断
            Assert.equals(password, rpassword, "两次密码输入不一致");

            //4.保存操作
            UserInfo info = new UserInfo();
            info.setPhone(phone);
            info.setNickname(nickname);
            info.setPassword(password);
            info.setGender(UserInfo.GENDER_NONE);
            info.setCity("广州");
            info.setLevel(1);
            userInfoMapper.insert(info);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @Override
    public AjaxResult userLogin(String phone, String password) {
        AjaxResult result = new AjaxResult();
        try {
            //1.非空验证
            Assert.hasLength(phone, "手机号不能为空");
            Assert.hasLength(password, "密码不能为空");

            //2.登录验证
            UserInfo userInfo = userInfoMapper.checkLogin(phone, password);
            Assert.notNull(userInfo, "手机号和密码不匹配");

            //验证通过,将对象信息存入Redis中
            //1.生成token
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            //2.存入redis
            loginInfoCacheService.setLoginInfo(token, JSON.toJSONString(userInfo));
            //3.设置给result
            result.setData(token);

        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    @Override
    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }

    /**
     * 修改用户信息
     *
     * @param userInfo
     */
    public UserInfo updateUserBase(UserInfo userInfo) {
        //1.修改个人信息
        try {
            userInfoMapper.updateBaseById(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2.重新查询个人信息
        UserInfo user = userInfoMapper.selectById(userInfo.getId());
        return user;
    }

    /**
     * 验证码
     *
     * @param code
     * @param phone
     * @return
     */
    public AjaxResult checkPhoneAndverifyCode(String code, String phone) {
        AjaxResult result = new AjaxResult();
        try {
            //1.验证是否填入验证码
            Assert.hasLength(code, "请填入验证码");
            String verifyCode4Redis = verifyCodeCacheService.getVerifyCode(phone);
            Assert.equalsIgnoreCase(code, verifyCode4Redis, "验证码有误");
            //2.获取redis中存的验证码

        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /**
     * 头像修改
     *
     * @param userInfo
     * @return
     */
    public UserInfo updateUserHead(UserInfo userInfo, String headImgUrl) {
        //1.修改头像
        try {
            userInfoMapper.updateHeadById(headImgUrl, userInfo.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2.重新查询个人信息
        UserInfo user = userInfoMapper.selectById(userInfo.getId());
        return user;
    }

    /**
     * 修改手机号
     *
     * @param userInfo
     * @param phone
     * @return
     */
    public UserInfo updateUserPhone(UserInfo userInfo, String phone) {
        try {
            userInfoMapper.updatePhoneById(phone, userInfo.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2.重新查询个人信息
        UserInfo user = userInfoMapper.selectById(userInfo.getId());
        return user;
    }

    /**
     * 获取用户的所有关注用户
     *
     * @param userId
     * @return
     */
    public List<UserInfo> getConcernsUser(Long userId) {
        return userInfoMapper.selectConcernsUser(userId);
    }

    /**
     * 获取指定用户的个人信息
     *
     * @param hisId
     * @return
     */
    public UserInfo getHisUserById(Long hisId) {
        return userInfoMapper.selectById(hisId);
    }

    /**
     * 查询用户的关注总数
     *
     * @param userId
     * @return
     */
    public Integer getUserCount(Long userId) {
        Integer userCount = userInfoMapper.selectUserCount(userId);
        if (userCount == null) {
            return 0;
        }
        return userCount;
    }

    /**
     * 查询被关注的人
     *
     * @param userId
     * @return
     */
    public Integer getBeUserCount(Long userId) {
        Integer beUserCount = userInfoMapper.selectBeUserCount(userId);
        if (beUserCount == null) {
            return 0;
        }
        return beUserCount;
    }

    /**
     * 存入用户的关注
     *
     * @param beConcernId
     * @param id
     * @return false取消关注 true进行关注
     */
    public boolean saveUserConcern(Long beConcernId, Long id) {
        //1.判断是否已经关注
        List<Long> beUser = userInfoMapper.selectIsConcernsUser(id);
        if (beUser.size() != 0 && beUser != null) {
            for (Long aLong : beUser) {
                if (aLong == beConcernId) {//查询是否有关注的用户
                    //2.删除关注关系
                    userInfoMapper.deleteUserConcern(beConcernId, id);
                    return false;
                }
            }
        }
        userInfoMapper.insertUserConcern(beConcernId, id);
        return true;
    }

    /**
     * 存入用户的访问量
     *
     * @param
     */
    public void saveVisitorsRank(int visitorsCount, Long userId) {
        userInfoMapper.updateVisitorsRank(visitorsCount, userId);
    }

    /**
     * 通过名称查询用户
     *
     * @param name
     * @return
     */
    public UserInfo getUserByName(String name) {
        return userInfoMapper.selectUserByName(name);
    }

    /**
     * 建立黑名单关系
     *
     * @param id
     * @param blackId
     */
    public void saveOrDeleteBlackList(Long id, Long blackId) {
        //1.判断是否已添加黑名单
        List<Long> longList = userInfoMapper.selectBackListById(id);
        if (longList != null && longList.size() > 0) {
            //2.若添加了--取消黑名单
            userInfoMapper.deleteBackList(id, blackId);
        } else {
            //3.若没添加--建立黑名单
            userInfoMapper.insertBackList(id, blackId);
        }
    }

    /**
     * 获取黑名单
     *
     * @param id
     * @return
     */
    public List<UserInfo> getBlackList(Long id) {
        return userInfoMapper.selectBlackList(id);
    }

}
